package com.shigu.user.action;

import com.shigu.AppLoginResponse;
import com.shigu.MallResponse;
import com.shigu.TokenRequest;
import com.shigu.exceptions.WapException;
import com.shigu.phoneCode.enums.PhoneCodeType;
import com.shigu.phoneCode.service.PhoneCodeService;
import com.shigu.user.bo.*;
import com.shigu.user.service.AppLoginService;
import com.shigu.user.service.MallTokenService;
import com.shigu.user.vo.AppUserResponse;
import com.shigu.weixin.exceptions.UtilsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;

@Controller
@RequestMapping("/wapsjson")
public class AppLoginController {
    @Autowired
    AppLoginService appLoginService;
    @Autowired
    MallTokenService mallTokenService;
    @Autowired
    PhoneCodeService phoneCodeService;

    @RequestMapping("registerCodeCheck")
    @ResponseBody
    public MallResponse registerCodeCheck (@Valid PhoneCodeRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        if (!phoneCodeService.checkPhoneCode(request.getTelephone(),request.getPhoneCode(), PhoneCodeType.REGISTER,30*60*1000)) {
            throw new WapException("验证码错误");
        }
        return new MallResponse().success();
    }

    @RequestMapping("passwordCodeCheck")
    @ResponseBody
    public MallResponse passwordCodeCheck (@Valid PhoneCodeRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        if (!phoneCodeService.checkPhoneCode(request.getTelephone(),request.getPhoneCode(), PhoneCodeType.PASSWORD,15*60*1000)) {
            throw new WapException("验证码错误");
        }
        return new MallResponse().success();
    }

    @RequestMapping("registeCode")
    @ResponseBody
    public synchronized MallResponse registeCode(@Valid PhoneRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        return appLoginService.registeCode(request.getTelephone());
    }

    @RequestMapping("pwdLogin")
    @ResponseBody
    public AppLoginResponse pwdLogin(@Valid UserLoginRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        Long userId = appLoginService.pwdLogin(request.getTelephone(), request.getPassword(),request.getCid());
        String token = mallTokenService.userIdToToken(userId);
        return new AppLoginResponse(token).success();
    }

    @RequestMapping("userRegister")
    @ResponseBody
    public synchronized  AppLoginResponse userRegister(@Valid @RequestBody RegitserRequest request, BindingResult result, HttpSession session) throws WapException, IOException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        Long userId =  appLoginService.userRegister(request.getUsername(), request.getTelephone(),
                                                      request.getPassword(),request.getImgData(),
                                                      request.getInviteCode(),request.getVersion(),request.getOs());
        String token = mallTokenService.userIdToToken(userId);
        return new AppLoginResponse(token).success();
    }

    @RequestMapping("submitRegisterInfo")
    @ResponseBody
    public synchronized MallResponse submitRegist(@Valid WebRegistRequest request,BindingResult result) throws WapException {
        if (!phoneCodeService.checkPhoneCode(request.getTelephone(),request.getVerCode(), PhoneCodeType.REGISTER,30*60*1000)) {
            throw new WapException("验证码错误");
        }
        return appLoginService.submitRegist(request.getTelephone(),request.getPassword(),request.getCode());
    }


    @RequestMapping("modPwdCode")
    @ResponseBody
    public MallResponse modPwdCode(@Valid PhoneRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        return   appLoginService.modPwdCode(request.getTelephone());
    }

    @RequestMapping("modPwd")
    @ResponseBody
    public AppLoginResponse modPwd(@Valid ModPwdRequest request, BindingResult result) throws WapException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        Long userId = appLoginService.modPwd(request.getTelephone(),request.getNewPassword());
        String token = mallTokenService.userIdToToken(userId);
        return new AppLoginResponse(token).success();
    }

    @RequestMapping("getAppUser")
    @ResponseBody
    public AppUserResponse getAppUser(TokenRequest request) {
        Long userId = mallTokenService.selUserIdByToken(request.getToken());
        return appLoginService.getAppUser(userId);
    }

    @RequestMapping("changeHeadUrl")
    @ResponseBody
    public MallResponse changeHeadUrl(@Valid @RequestBody HeadRequest request,BindingResult result) throws WapException, IOException {
        if (result.hasErrors()) {
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        Long userId = mallTokenService.selUserIdByToken(request.getToken());
        return appLoginService.changeHeadUrl(userId,request.getImgData());
    }

    @RequestMapping("bindWxUser")
    @ResponseBody
    public MallResponse bindWxUser(@Valid BindWxUserRequest request,BindingResult result) throws WapException, UtilsException {
        if(result.hasErrors()){
            throw new WapException(result.getFieldError().getDefaultMessage());
        }
        Long mallUserId = mallTokenService.selUserIdByToken(request.getToken());
        return appLoginService.bindWxUser(request.getUnionId(),mallUserId,request.getWxUserName(),
                                            request.getOpenId(),request.getAvatarUrl());
    }
}
